import { defineStore } from "pinia";
import { ref } from "vue";
import { getCurrentUser, userLogout } from "@/api/user";
import { message } from "ant-design-vue";

export const currentUserStore = defineStore("counter", () => {
  const loginUser = ref<any>({
    userName: "未登录",
  });
  //远程获取用户登录信息
  async function fetchLoginUser() {
    const res = await getCurrentUser();
    if (res.data.code == 0 && res.data.data) {
      loginUser.value = res.data.data;
    }
  }

  //单独设置用户信息
  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser;
  }

  async function logout() {
    const res = await userLogout();
    if (res.data.code == 0) {
      if (res.data.data === true) {
        message.success("退出登录成功");
        loginUser.value = {
          userName: "未登录",
        };
      }
    }
    // 刷新一下所在页面
    window.location.reload();
  }

  return { loginUser, fetchLoginUser, setLoginUser, logout };
});
